<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { useDark, useToggle } from '@vueuse/core'

// 响应式状态
const todos = ref([])
const newTodo = ref('')
const filter = ref('all')
const isDark = useDark()
const toggleDark = useToggle(isDark)
const apiBaseUrl = 'https://kksoqvldrbye.sealoshzh.site'

// API函数
async function fetchTodos() {
  try {
    const response = await fetch(`${apiBaseUrl}/api/get-todo`)
    const data = await response.json()
    todos.value = data
  } catch (error) {
    console.error('获取待办事项失败:', error)
  }
}

async function addTodoApi(todoText) {
  try {
    const response = await fetch(`${apiBaseUrl}/api/add-todo`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        value: todoText,
        isCompleted: false
      })
    })
    const newTodo = await response.json()
    return newTodo
  } catch (error) {
    console.error('添加待办事项失败:', error)
    return null
  }
}

async function updateTodoApi(id) {
  try {
    const response = await fetch(`${apiBaseUrl}/api/update-todo/${id}`, {
      method: 'POST'
    })
    const updatedTodo = await response.json()
    return updatedTodo
  } catch (error) {
    console.error('更新待办事项失败:', error)
    return null
  }
}

async function deleteTodoApi(id) {
  try {
    const response = await fetch(`${apiBaseUrl}/api/del-todo/${id}`, {
      method: 'POST'
    })
    const result = await response.json()
    return result
  } catch (error) {
    console.error('删除待办事项失败:', error)
    return null
  }
}

// 初始化加载数据
onMounted(() => {
  fetchTodos()
})

// 计算属性
const filteredTodos = computed(() => {
  if (filter.value === 'completed') {
    return todos.value.filter(todo => todo.isCompleted)
  } else if (filter.value === 'active') {
    return todos.value.filter(todo => !todo.isCompleted)
  }
  return todos.value
})

const completedCount = computed(() => todos.value.filter(todo => todo.isCompleted).length)
const totalCount = computed(() => todos.value.length)
const completionRate = computed(() => {
  return totalCount.value ? Math.round((completedCount.value / totalCount.value) * 100) : 0
})

// 方法
async function addTodo() {
  if (newTodo.value.trim()) {
    const addedTodo = await addTodoApi(newTodo.value.trim())
    if (addedTodo) {
      todos.value.push(addedTodo)
      newTodo.value = ''
    }
  }
}

async function toggleTodo(id) {
  const updatedTodo = await updateTodoApi(id)
  if (updatedTodo) {
    const index = todos.value.findIndex(todo => todo._id === id)
    if (index !== -1) {
      todos.value[index] = updatedTodo
    }
  }
}

async function removeTodo(id) {
  const result = await deleteTodoApi(id)
  if (result && result.message === "删除成功") {
    todos.value = todos.value.filter(todo => todo._id !== id)
  }
}
</script>

<template>
  <div class="todo-app" :class="{ 'dark-mode': isDark }">
    <div class="app-container">
      <header class="app-header">
        <h1>我的待办事项</h1>
        <button class="theme-toggle" @click="toggleDark()">
          <span v-if="isDark">🌞</span>
          <span v-else>🌙</span>
        </button>
      </header>

      <div class="task-input">
        <input 
          type="text" 
          v-model="newTodo" 
          @keyup.enter="addTodo" 
          placeholder="添加新的待办事项..." 
        />
        <button class="add-btn" @click="addTodo">
          <span class="add-icon">+</span>
        </button>
      </div>

      <div class="stats-container">
        <div class="completion-stats">
          <div class="progress-bar">
            <div class="progress" :style="{ width: completionRate + '%' }"></div>
          </div>
          <div class="stats-text">
            完成进度: {{ completionRate }}% ({{ completedCount }}/{{ totalCount }})
          </div>
        </div>
        <div class="filter-buttons">
          <button 
            :class="{ active: filter === 'all' }" 
            @click="filter = 'all'"
          >全部</button>
          <button 
            :class="{ active: filter === 'active' }" 
            @click="filter = 'active'"
          >未完成</button>
          <button 
            :class="{ active: filter === 'completed' }" 
            @click="filter = 'completed'"
          >已完成</button>
        </div>
      </div>

      <div class="todo-list" v-if="filteredTodos.length">
        <div 
          v-for="todo in filteredTodos" 
          :key="todo._id" 
          class="todo-item"
          :class="{ 'completed': todo.isCompleted }"
        >
          <div class="todo-content">
            <label class="checkbox-container">
              <input 
                type="checkbox" 
                :checked="todo.isCompleted"
                @change="toggleTodo(todo._id)"
              />
              <span class="checkmark"></span>
            </label>
            <span class="todo-text">{{ todo.value }}</span>
          </div>
          <button class="delete-btn" @click="removeTodo(todo._id)">×</button>
        </div>
      </div>
      <div class="empty-state" v-else>
        <p>{{ filter === 'all' ? '没有待办事项，添加一个吧！' : 
              filter === 'active' ? '没有未完成的事项' : 
              '没有已完成的事项' }}</p>
      </div>
    </div>
  </div>
</template>

<style>
@import '@mdi/font/css/materialdesignicons.min.css';

:root {
  --primary-color: #4361ee;
  --primary-light: #4cc9f0;
  --secondary-color: #f72585;
  --text-color: #333;
  --text-light: #666;
  --bg-color: #fff;
  --bg-secondary: #f5f7fa;
  --border-color: #eaeaea;
  --shadow-color: rgba(0, 0, 0, 0.1);
  
  --border-radius: 12px;
  --spacing: 24px;
  --transition-speed: 0.3s;
}

.dark-mode {
  --primary-color: #4361ee;
  --primary-light: #4cc9f0;
  --secondary-color: #f72585;
  --text-color: #f5f7fa;
  --text-light: #bbbfc4;
  --bg-color: #121212;
  --bg-secondary: #1e1e1e;
  --border-color: #2a2a2a;
  --shadow-color: rgba(0, 0, 0, 0.5);
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 
               Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
  line-height: 1.6;
  color: var(--text-color);
  background-color: var(--bg-color);
  transition: background-color var(--transition-speed) ease, 
              color var(--transition-speed) ease;
}

.todo-app {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  padding: var(--spacing);
  background-color: var(--bg-color);
  transition: background-color var(--transition-speed) ease;
}

.app-container {
  width: 100%;
  max-width: 800px;
  padding: var(--spacing);
  border-radius: var(--border-radius);
  background-color: var(--bg-secondary);
  box-shadow: 0 10px 30px var(--shadow-color);
}

/* 头部样式 */
.app-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: var(--spacing);
}

.app-header h1 {
  font-size: 2.5rem;
  font-weight: 700;
  background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

.theme-toggle {
  background: none;
  border: none;
  font-size: 1.5rem;
  cursor: pointer;
  padding: 8px;
  border-radius: 50%;
  transition: background-color var(--transition-speed) ease;
}

.theme-toggle:hover {
  background-color: var(--border-color);
}

/* 输入框样式 */
.task-input {
  display: flex;
  margin-bottom: var(--spacing);
}

.task-input input {
  flex: 1;
  padding: 16px;
  border: 2px solid var(--border-color);
  border-radius: var(--border-radius);
  background-color: var(--bg-color);
  color: var(--text-color);
  font-size: 1rem;
  transition: border-color var(--transition-speed) ease, 
              box-shadow var(--transition-speed) ease;
}

.task-input input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(67, 97, 238, 0.3);
}

.add-btn {
  margin-left: 10px;
  width: 50px;
  border: none;
  border-radius: var(--border-radius);
  background: linear-gradient(135deg, var(--primary-color), var(--primary-light));
  color: white;
  font-size: 1.5rem;
  cursor: pointer;
  transition: transform var(--transition-speed) ease, 
              opacity var(--transition-speed) ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-btn:hover {
  transform: translateY(-2px);
}

.add-btn:active {
  transform: translateY(0);
}

.add-icon {
  font-size: 1.8rem;
  line-height: 1;
}

/* 统计和过滤器样式 */
.stats-container {
  margin-bottom: var(--spacing);
}

.completion-stats {
  margin-bottom: 15px;
}

.progress-bar {
  height: 8px;
  background-color: var(--border-color);
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 8px;
}

.progress {
  height: 100%;
  background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
  transition: width 0.5s ease;
}

.stats-text {
  color: var(--text-light);
  font-size: 0.9rem;
}

.filter-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.filter-buttons button {
  padding: 8px 16px;
  border: none;
  border-radius: 20px;
  background-color: var(--bg-color);
  color: var(--text-light);
  cursor: pointer;
  transition: all var(--transition-speed) ease;
}

.filter-buttons button.active {
  background-color: var(--primary-color);
  color: white;
}

.filter-buttons button:hover:not(.active) {
  background-color: var(--border-color);
}

/* 待办事项列表样式 */
.todo-list {
  margin-top: var(--spacing);
}

.todo-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  margin-bottom: 12px;
  border-radius: var(--border-radius);
  background-color: var(--bg-color);
  box-shadow: 0 2px 8px var(--shadow-color);
  transition: transform var(--transition-speed) ease, 
              box-shadow var(--transition-speed) ease,
              opacity var(--transition-speed) ease;
}

.todo-item.completed {
  opacity: 0.8;
}

.todo-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px var(--shadow-color);
}

.todo-content {
  display: flex;
  align-items: center;
  flex: 1;
  height: 30px;
}

.todo-text {
  margin-left: 12px;
  transition: color var(--transition-speed) ease,
              text-decoration var(--transition-speed) ease;
  line-height: 30px;
  display: flex;
  align-items: center;
}

.todo-item.completed .todo-text {
  text-decoration: line-through;
  color: var(--text-light);
}

/* 自定义复选框 */
.checkbox-container {
  display: flex;
  align-items: center;
  position: relative;
  padding-left: 35px;
  cursor: pointer;
  user-select: none;
  height: 30px;
}

.checkbox-container input {
  position: absolute;
  opacity: 0;
  cursor: pointer;
  height: 0;
  width: 0;
}

.checkmark {
  position: absolute;
  top: 4px;
  left: 0;
  height: 22px;
  width: 22px;
  border-radius: 4px;
  border: 2px solid var(--border-color);
  background-color: var(--bg-color);
  transition: all var(--transition-speed) ease;
}

.checkbox-container:hover .checkmark {
  border-color: var(--primary-color);
}

.checkbox-container input:checked ~ .checkmark {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.checkmark:after {
  content: "";
  position: absolute;
  display: none;
}

.checkbox-container input:checked ~ .checkmark:after {
  display: block;
}

.checkbox-container .checkmark:after {
  left: 7px;
  top: 3px;
  width: 5px;
  height: 10px;
  border: solid white;
  border-width: 0 2px 2px 0;
  transform: rotate(45deg);
}

/* 删除按钮 */
.delete-btn {
  background: none;
  border: none;
  color: var(--text-light);
  font-size: 1.5rem;
  cursor: pointer;
  opacity: 0.5;
  transition: opacity var(--transition-speed) ease,
              color var(--transition-speed) ease;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  margin: 0;
}

.todo-item:hover .delete-btn {
  opacity: 1;
}

.delete-btn:hover {
  color: var(--secondary-color);
  background-color: rgba(247, 37, 133, 0.1);
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: var(--spacing);
  color: var(--text-light);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .app-container {
    padding: 16px;
  }
  
  .app-header h1 {
    font-size: 2rem;
  }
  
  .task-input input {
    padding: 12px;
  }
  
  .filter-buttons {
    flex-wrap: wrap;
  }
}

@media (max-width: 480px) {
  .app-header h1 {
    font-size: 1.8rem;
  }
  
  .app-container {
    padding: 12px;
  }
  
  .filter-buttons button {
    padding: 6px 12px;
    font-size: 0.9rem;
  }
}
</style>
